<template>
    <div class="bg" v-loading="loading">
      <div class="login">
        <div class="login-left"><img src="../../assets/images/login/login.jpg" alt="教务系统" class="login-img"></div>
        <div class="login-right">
          <h2 class="text-center zstu-edu">区块链学院学分管理系统</h2>
<!--          登录-->
          <template v-if="active===1">
            <el-form :model="ruleForm" ref="ruleFormsss" :rules="rules" label-width="100px" class="demo-ruleForm">
              <el-form-item label="学工号" prop="account">
                <el-input v-model="ruleForm.account" class="el-size" placeholder="请输入学工号(学号/邮箱)" clearable autofocus="true" auto-complete="new-password"></el-input>
              </el-form-item>
              <el-form-item label="密 码" prop="password">
                <el-input v-model="ruleForm.password" class="el-size" placeholder="请输入密码" show-password clearable auto-complete="new-password"></el-input>
              </el-form-item>
              <el-row>
                <el-col :span="24" :offset="6" class="text-center user-select">
                  <el-radio-group v-model="ruleForm.radio">
                    <el-radio label="stu">学生</el-radio>
                    <el-radio label="mana">团支书</el-radio>
                    <el-radio label="admin">管理员</el-radio>
                  </el-radio-group>
                </el-col>
              </el-row>
              <el-form-item>
                <el-button type="primary" :loading="isLoading" round class="el-size" @click="submitForm">登录</el-button>
              </el-form-item>
            </el-form>
            <div class="login-msg">
              <span>默认密码：123456,第一次登录后将重置密码</span>
              <span class="forget-pass" @click="active=2">注册</span>
              <span class="forget-pass">|</span>
              <span class="forget-pass" @click="active=3">忘记密码</span>
            </div>
          </template>
<!--          注册-->
          <template v-if="active===2">
            <el-form :model="register_ruleForm" ref="ruleFormsss" :rules="rules" label-width="100px" class="demo-ruleForm">
              <el-form-item label="邮箱" prop="email">
                <el-row>
                  <el-input v-model="register_ruleForm.email"  class="el-size" placeholder="请输入邮箱" clearable autofocus="true" auto-complete="new-password"></el-input>
                  <el-button type="primary" size="mini" @click="getstoreId">获取验证码</el-button>
                </el-row>
              </el-form-item>
              <el-form-item label="验证码" prop="storeId">
                <el-input v-model="register_ruleForm.storeId" class="el-size" placeholder="请输入验证码"  clearable auto-complete="new-password"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :loading="isLoading" round class="el-size" @click="registerForm">注册</el-button>
              </el-form-item>
            </el-form>
            <div class="login-msg register_msg">
              <span>默认密码：123456,第一次登录后将重置密码</span>
              <span class="forget-pass" @click="active=1">登录</span>
              <span class="forget-pass">|</span>
              <span class="forget-pass" @click="active=3">忘记密码</span>
            </div>
          </template>
<!--          忘记密码-->
          <template v-if="active===3">
            <el-form :model="backRuleForm" ref="ruleFormsss" :rules="rules" label-width="100px" class="demo-ruleForm" style="margin-top: -32px">
              <el-form-item label="邮箱" prop="email">
                <el-row>
                  <el-input v-model="backRuleForm.email" class="el-size" placeholder="请输入邮箱" clearable autofocus="true" auto-complete="new-password"></el-input>
                  <el-button type="primary" size="mini" @click="getBackStoreId">获取验证码</el-button>
                </el-row>
              </el-form-item>
              <el-form-item label="验证码" prop="storeId">
                <el-input v-model="backRuleForm.storeId" class="el-size" placeholder="请输入验证码"  clearable auto-complete="new-password"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="backRuleForm.newPassword" class="el-size" placeholder="请输入新密码"  show-password clearable auto-complete="new-password"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="repeatPassword">
                <el-input v-model="backRuleForm.repeatPassword" class="el-size" placeholder="请再次输入新密码" show-password clearable auto-complete="new-password"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :loading="isLoading" round class="el-size" @click="backForm">找回密码</el-button>
              </el-form-item>
            </el-form>
            <div class="login-msg back_msg">
              <span>默认密码：123456,第一次登录后将重置密码</span>
              <span class="forget-pass" @click="active=1">登录</span>
              <span class="forget-pass">|</span>
              <span class="forget-pass" @click="active=2">注册</span>
            </div>
          </template>
<!--          重置密码-->
          <template v-if="active===4">
            <el-tooltip class="item" effect="dark" content="经系统检测，你为第一次登录，请重置你的账号密码" placement="top" hide-after="10000" >
            <el-form :model="ResetRuleForm" ref="ruleFormsss" :rules="rules" label-width="100px" class="demo-ruleForm" >
              <el-form-item label="学号" prop="account">
                <el-input v-model="ResetRuleForm.account" class="el-size" placeholder="请输入学号"   clearable auto-complete="new-password"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="resetNewPassword">
                <el-input v-model="ResetRuleForm.resetNewPassword" class="el-size" placeholder="请输入新密码"  show-password clearable auto-complete="new-password"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="resetPassword">
                <el-input v-model="ResetRuleForm.resetPassword" class="el-size" placeholder="请再次输入新密码" show-password clearable auto-complete="new-password"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :loading="isLoading" round class="el-size" @click="ResetForm">重置密码</el-button>
              </el-form-item>
            </el-form>
            </el-tooltip>
          </template>
        </div>
      </div>
    </div>
</template>
<script lang="ts">
import {ElMessage} from 'element-plus';
import {superLogin} from '@/network/admin/superLogin';
import {studentLogin} from '@/network/student/studentLogin';
import {managerLogin} from '@/network/manager/managerLogin'
import qs from 'qs';
import {computed, ref, defineComponent, getCurrentInstance, onMounted, reactive, toRefs, unref} from "vue";
import {Store} from "vuex";
import {getStoreId} from "@/network/global/getStoreId";
import {registerUser} from "@/network/global/register";
import {resetPassword} from "@/network/global/resetPassword";
import {backPassword} from "@/network/global/backPassword";

export default {
  data(){
    return{
      active:1,
      isLoading: false,
      disabled: false
    }
  },
  setup(props: any) {
    const ruleFormsss = ref(null);
    const {proxy}: any = getCurrentInstance();
    // const router=useRouter();
    // 定义变量
    const ruleForm = reactive({
      account: '',
      password: '',
      radio:'stu'

    })
    const register_ruleForm=reactive({
      email:'',
      storeId:'',
      password:''
    })
    const backRuleForm=reactive({
      email:'',
      storeId:'',
      newPassword:'',
      repeatPassword:''
    })
    const ResetRuleForm=reactive({
      email:'',
      account:'',
      resetNewPassword:'',
      resetPassword:''
    })
    const TooLPitState=reactive({
      LoginState:false,
      ResetState:false
    })

    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== proxy.backRuleForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var validatePass22 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== proxy.ResetRuleForm.resetNewPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    const rules = {
      account: [
        { required: true, message: '请输入学工号', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
      ],
      resetNewPassword: [
        { required: true, message: '请输入重置密码', trigger: 'blur' },
      ],
      repeatPassword:[
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {validator:validatePass2,message: '两次输入密码不一致！',trigger: ['blur', 'change']}
      ],
      resetPassword:[
        { required: true, message: '请再次输入重置密码', trigger: 'blur' },
        {validator:validatePass22,message: '两次输入密码不一致！',trigger: ['blur', 'change']}
      ],
      email:[
        {required:true,message:'请输入邮箱',trigger:'blur'},
       // {validator:checkPhone,required:true,trigger:'blur'}
        {type:'email',message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
      ],
      storeId:[
        {required:true,message:'请输入验证码',trigger:'blur'},
        {min:4,max:4,message: '请输入正确的验证码',trigger: ['blur', 'change']}
      ]
    }
//注册验证码
    const  getstoreId=async ()=>{
      const data = {email:register_ruleForm.email}
      try {
        getStoreId(data).then(() => {
          proxy.$message({
            message: "已发送验证码",
            type: "success"
          });
        })
            .catch(() => {
              proxy.$message({
                message: "请求超时，请检查网络连接",
                type: "error"
              });
            });
        console.log(data)
      } catch (error) {
      }

    }

//忘记密码验证码
    const  getBackStoreId=async ()=>{
      const data = {email:backRuleForm.email}
      if(backRuleForm.email=="") return
      try {
        getStoreId(data).then(() => {
          proxy.$message({
            message: "已发送验证码",
            type: "success"
          });
        })
            .catch(() => {
              proxy.$message({
                message: "请求超时，请检查网络连接",
                type: "error"
              });
            });
        console.log(data)
      } catch (error) {
      }

    }


    const registerForm=async ()=>{
      const form = unref(ruleFormsss);
      if (!form) {return}
      try {
        await (form as any).validate(undefined)
        register_ruleForm.password='123456'
        const data = qs.stringify(register_ruleForm)
        registerUser(data).then((result: any) => {
          //前后端连接成功
          console.log("前后端连接成功")
          //打印返回结果
          console.log("打印返回结果")
          console.log(result)
          //打印返回结果状态，有没有正确匹配到用户
          console.log(result.data.status)
          //打印返回用户的类型
          console.log(result.data.result.power)
          const msg = result.data.msg;
          //打印返回结果状态，
          if (result.data.status == 1) {
            ElMessage.error(msg);
          } else {
            console.log(msg)
            ElMessage.success({
              message: msg, type: 'success'
            });
            //
            // localStorage.setItem('Id', result.data.result[0].id)
            // localStorage.setItem('Name', result.data.result[0].name)
            // console.log("临时" + result.data.result[0].id)
            // console.log(localStorage.getItem('Name'))
            if(proxy.active===2){
              proxy.active=1
            }

          }
        }).catch(() => {
          console.log("no")
          const msg = "注册失败！请稍后尝试！";
          ElMessage.error(msg);
        })

        //数据打印
        console.log(data)
        console.log("submit")
        const {email, storeId,} = register_ruleForm;
        console.log(email, storeId)


      } catch (error) {
      }
    }

    const ResetForm=async ()=>{
      const form = unref(ruleFormsss);
      console.log(ResetRuleForm.email+':email')
      TooLPitState.ResetState=true
      if (!form) {return}
      try {

        await (form as any).validate(undefined)
        const ResetRuleForm_data={
          email:ResetRuleForm.email,
          account:ResetRuleForm.account,
          password:ResetRuleForm.resetNewPassword
        }
        const data = qs.stringify(ResetRuleForm_data)
        resetPassword(data).then((result: any) => {
          console.log(result)
          const msg = result.data.msg;
          //打印返回结果状态，
          if (result.data.status == 1) {
            ElMessage.error(msg);
          } else {
            console.log(msg)
            ElMessage.success({
              message: msg, type: 'success'
            });
            if(proxy.active===4){
              proxy.active=1
            }

          }
        }).catch(() => {
          console.log("no")
          const msg = "重置密码失败！请稍后尝试！";
          ElMessage.error(msg);
        })

        //数据打印
        console.log(data)
        console.log("Reset")
      } catch (error) {
      }
    }


    const backForm=async ()=>{
      const form = unref(ruleFormsss);
      console.log(backRuleForm.email+':email')
      if (!form) {return}
      try {

        await (form as any).validate(undefined)
        const backRuleForm_data={
          email:backRuleForm.email,
          storeId:backRuleForm.storeId,
          password:backRuleForm.newPassword
        }
        const data = qs.stringify(backRuleForm_data)
        backPassword(data).then((result: any) => {
          console.log(result)
          const msg = result.data.msg;
          //打印返回结果状态，
          if (result.data.status == 1) {
            ElMessage.error(msg);
          } else {
            console.log(msg)
            ElMessage.success({
              message: msg, type: 'success'
            });
            if(proxy.active===3){
              proxy.active=1
            }

          }
        }).catch(() => {
          console.log("no")
          const msg = "重置密码失败！请稍后尝试！";
          ElMessage.error(msg);
        })

        //数据打印
        console.log(data)
        console.log("back")
      } catch (error) {
      }
    }


    const submitForm = async () => {
      const form = unref(ruleFormsss);
      TooLPitState.LoginState=true
      if (!form) {return}
      try {
         await (form as any).validate(undefined)
          const data = qs.stringify(ruleForm)

          if (ruleForm.radio === 'stu') {
            proxy.studentUserLogin(data)
          } else if (ruleForm.radio === 'mana') {
            proxy.managerUserLogin(data)
          } else if (ruleForm.radio === 'admin') {
            proxy.superUserLogin(data)
          }
          console.log(ruleForm.radio);
          //数据打印
          console.log(data)
          console.log("submit")
          const {account, password,} = ruleForm;
          console.log(account, password)

      } catch (error) {
      }
    }


    function superUserLogin(data: any) {
      superLogin(data).then(result => {
        //前后端连接成功
        console.log("前后端连接成功")
        //打印返回结果
        console.log("打印返回结果")
        console.log(result)
        //打印返回结果状态，有没有正确匹配到用户

        console.log(result.data.status)
        //打印返回用户的类型
        console.log(result.data.result.power)
        const msg = result.data.msg;
        //打印返回结果状态，
        if (result.data.status == 1) {
          ElMessage.error(msg);
        } else {
          console.log(msg)
          ElMessage.success({
            message: msg, type: 'success'
          });
          //保存登录的用户名
          localStorage.setItem('AdminId', result.data.result[0].aid)
          localStorage.setItem('AdminName', result.data.result[0].account)
          sessionStorage.setItem('isLogin','3')
          console.log("临时" + result.data.result[0].id)
          console.log(localStorage.getItem('AdminName'))
          window.location.href = "http://localhost:8080/admin";
        }
      }).catch(() => {
        console.log("no")
        const msg = "登录失败！请稍后尝试！";
        ElMessage.error(msg);
      })
    }


    function studentUserLogin(data: any) {
      studentLogin(data).then((result: any) => {
        //前后端连接成功
        console.log("前后端连接成功")
        //打印返回结果
        console.log("打印返回结果")
        console.log(result)
        //打印返回结果状态，有没有正确匹配到用户
        console.log(result.data.status)
        //打印返回用户的类型
        console.log(result.data.result.power)
        const msg = result.data.msg;
        //打印返回结果状态，
        if (result.data.status == 1) {
          ElMessage.error(msg);
        } else {
          if(ruleForm.password==='123456'){
            if(proxy.active===1){
              proxy.active=4
              ResetRuleForm.email=ruleForm.account
            }}
          else{
            console.log(TooLPitState)
            console.log(TooLPitState.LoginState===TooLPitState.ResetState)
            if(TooLPitState.LoginState===TooLPitState.ResetState){
              localStorage.setItem('TooLPitNoSeen', 'false')
            }else {
              localStorage.setItem('TooLPitNoSeen', 'true')
            }
            console.log(msg)
            ElMessage.success({
              message: msg, type: 'success'
            });

            localStorage.setItem('StudentId', result.data.result[0].id)
            localStorage.setItem('StudentName', result.data.result[0].name)
            sessionStorage.setItem('isLogin','1')
            console.log("临时" + result.data.result[0].id)
            console.log(localStorage.getItem('StudentName'))
             window.location.href = "http://localhost:8080/student";
          }
        }
      }).catch(() => {
        console.log("no")
        const msg = "登录失败！请稍后尝试！";
        ElMessage.error(msg);
      })
    }


    function managerUserLogin(data: any) {
      managerLogin(data).then((result: any) => {
        //前后端连接成功
        console.log("前后端连接成功")
        //打印返回结果
        console.log("打印返回结果")
        console.log(result)
        //打印返回结果状态，有没有正确匹配到用户
        console.log(result.data.status)
        //打印返回用户的类型
        console.log(result.data.result.power)
        const msg = result.data.msg;
        //打印返回结果状态，
        if (result.data.status == 1) {
          ElMessage.error(msg);
        } else {
          console.log(msg)
          ElMessage.success({
            message: msg, type: 'success'
          });

          localStorage.setItem('ManagerId', result.data.result[0].mid)
          localStorage.setItem('ManagerName', result.data.result[0].name)
          sessionStorage.setItem('isLogin','2')
          console.log("临时" + result.data.result[0].mid)
          console.log(localStorage.getItem('ManagerName'))
          //console.log(sessionStorage.getItem("isLogin"))
          window.location.href = "http://localhost:8080/manager";
          // if(sessionStorage.getItem("isLogin")==='2'){
          //   console.log("匹配采购")
          // }

          //
        }
      }).catch(() => {
        //console.log(qs.stringify(ruleForm))
        //window.location.href="http://localhost:8080/home";
        console.log("no")
        const msg = "登录失败！请稍后尝试！";
        ElMessage.error(msg);
      })
    }


    return {
      getBackStoreId,
      getstoreId,
      TooLPitState,
      ruleForm,
      register_ruleForm,
      rules,
      submitForm,
      registerForm,
      ResetForm,
      backForm,
      backRuleForm,
      ResetRuleForm,
      ruleFormsss,
      superUserLogin,
      studentUserLogin,
      managerUserLogin

    }
  }


}
</script>
<style scoped>
/*#login-wrapper {*/
/*  !* background: linear-gradient(#141e30, #243b55); *!*/
/*  background: radial-gradient(ellipse at bottom, #1b2735 0%, #090a0f 100%);*/
/*  height: 100%;*/
/*  overflow: hidden;*/
/*}*/
/*.login-box {*/
/*  position: absolute;*/
/*  top: 50%;*/
/*  left: 50%;*/
/*  width: 400px;*/
/*  padding: 40px;*/
/*  transform: translate(-50%, -50%);*/
/*  background: rgba(0, 0, 0, 0.8);*/
/*  box-sizing: border-box;*/
/*  box-shadow: 0 15px 25px rgba(0, 0, 0, 0.6);*/
/*  border-radius: 10px;*/
/*}*/

/*.login-box h2 {*/
/*  margin: 0 0 30px;*/
/*  padding: 0;*/
/*  color: #fff;*/
/*  text-align: center;*/
/*}*/

/*.login-box .user-box {*/
/*  position: relative;*/
/*}*/

/*.login-box .user-box input {*/
/*  width: 100%;*/
/*  padding: 10px 0;*/
/*  font-size: 16px;*/
/*  color: #fff;*/
/*  margin-bottom: 30px;*/
/*  border: none;*/
/*  border-bottom: 1px solid #fff;*/
/*  outline: none;*/
/*  background: transparent;*/
/*}*/
/*.login-box .user-box label {*/
/*  position: absolute;*/
/*  top: 0;*/
/*  left: 0;*/
/*  padding: 10px 0;*/
/*  font-size: 16px;*/
/*  color: #fff;*/
/*  pointer-events: none;*/
/*  transition: 0.5s;*/
/*}*/

/*.login-box .user-box input:focus ~ label,*/
/*.login-box .user-box input:valid ~ label {*/
/*  top: -20px;*/
/*  left: 0;*/
/*  color: #03e9f4;*/
/*  font-size: 12px;*/
/*}*/

/*.login-box form a {*/
/*  position: relative;*/
/*  display: inline-block;*/
/*  padding: 10px 20px;*/
/*  color: #03e9f4;*/
/*  font-size: 16px;*/
/*  text-decoration: none;*/
/*  text-transform: uppercase;*/
/*  overflow: hidden;*/
/*  transition: 0.5s;*/
/*  margin-top: 40px;*/
/*  letter-spacing: 4px;*/
/*}*/

/*.login-box a:hover {*/
/*  background: #03e9f4;*/
/*  color: #fff;*/
/*  border-radius: 5px;*/
/*  box-shadow: 0 0 5px #03e9f4, 0 0 25px #03e9f4, 0 0 50px #03e9f4, 0 0 100px #03e9f4;*/
/*}*/

/*.login-box a span {*/
/*  position: absolute;*/
/*  display: block;*/
/*}*/

/*.login-box a span:nth-child(1) {*/
/*  top: 0;*/
/*  left: -100%;*/
/*  width: 100%;*/
/*  height: 2px;*/
/*  background: linear-gradient(90deg, transparent, #03e9f4);*/
/*  animation: btn-anim1 1s linear infinite;*/
/*}*/

/*@keyframes btn-anim1 {*/
/*  0% {*/
/*    left: -100%;*/
/*  }*/
/*  50%,*/
/*  100% {*/
/*    left: 100%;*/
/*  }*/
/*}*/

/*.login-box a span:nth-child(2) {*/
/*  top: -100%;*/
/*  right: 0;*/
/*  width: 2px;*/
/*  height: 100%;*/
/*  background: linear-gradient(180deg, transparent, #03e9f4);*/
/*  animation: btn-anim2 1s linear infinite;*/
/*  animation-delay: 0.25s;*/
/*}*/

/*@keyframes btn-anim2 {*/
/*  0% {*/
/*    top: -100%;*/
/*  }*/
/*  50%,*/
/*  100% {*/
/*    top: 100%;*/
/*  }*/
/*}*/

/*.login-box a span:nth-child(3) {*/
/*  bottom: 0;*/
/*  right: -100%;*/
/*  width: 100%;*/
/*  height: 2px;*/
/*  background: linear-gradient(270deg, transparent, #03e9f4);*/
/*  animation: btn-anim3 1s linear infinite;*/
/*  animation-delay: 0.5s;*/
/*}*/

/*@keyframes btn-anim3 {*/
/*  0% {*/
/*    right: -100%;*/
/*  }*/
/*  50%,*/
/*  100% {*/
/*    right: 100%;*/
/*  }*/
/*}*/

/*.login-box a span:nth-child(4) {*/
/*  bottom: -100%;*/
/*  left: 0;*/
/*  width: 2px;*/
/*  height: 100%;*/
/*  background: linear-gradient(360deg, transparent, #03e9f4);*/
/*  animation: btn-anim4 1s linear infinite;*/
/*  animation-delay: 0.75s;*/
/*}*/

/*@keyframes btn-anim4 {*/
/*  0% {*/
/*    bottom: -100%;*/
/*  }*/
/*  50%,*/
/*  100% {*/
/*    bottom: 100%;*/
/*  }*/
/*}*/





.bg {
  background-color: #DDD;
  height: 100vh;
}
.login {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -ms-transform: translateY(-50%);	/* IE 9 */
  -moz-transform: translateY(-50%); 	/* Firefox */
  -webkit-transform: translateY(-50%); /* Safari 和 Chrome */
  -o-transform: translateY(-50%); 	/* Opera */
  display: flex;
  display: -webkit-flex;
  justify-content: center;
}
.login-right {
  width: 500px;
  height: 400px;
  background-color: #FFF;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}
.login-img {
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}
.register_msg{
  margin-top: 85px!important;
}
.user-select {
  margin-bottom: 1.4em;
}
.zstu-edu {
  margin: 2em;
  font-size: 1.8em;
  text-align: center
}
.el-size {
  width: 300px;
}
.login-msg {
  margin-top: 4em;
  font-size: 12px;
  color: #606266;
  display: flex;
  justify-content: space-around;
}
.back_msg{
  margin-top: 0em;
}
.forget-pass {
  cursor: pointer;
}
</style>
